#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* spiralOrder(int** matrix, int matrixSize, int* matrixColSize, int* returnSize);

int main()
{
	return 0;
}

int* spiralOrder(int** matrix, int matrixSize, int* matrixColSize, int* returnSize)
{
	if (!matrix || !matrixSize) return 0;

	int totalLength = matrixSize * *matrixColSize,
		size = 0;
	*returnSize = totalLength;
	int* res = calloc(totalLength, sizeof(int));

	int right = *matrixColSize - 1, bottom = matrixSize - 1, left = 0, top = 0;
	while (totalLength != size) {
		for (int i = left; i <= right; i++)
			res[size++] = matrix[top][i];
		top++;
		for (int i = top; i <= bottom && totalLength != size; i++)
			res[size++] = matrix[i][right];
		right--;
		for (int i = right; i >= left && totalLength != size; i--)
			res[size++] = matrix[bottom][i];
		bottom--;
		for (int i = bottom; i >= top && totalLength != size; i--)
			res[size++] = matrix[i][left];
		left++;
	}

	return res;
}
